﻿using System.Linq;
using System.Web.Mvc;
using JStore.Core.Commands;
using JStore.Core.Entities;
using JStore.Core.Enums;
using JStore.Tasks;
using JStore.Web.Controllers.CardTypes.ViewModels;
using SpeadFrm.Extensions;
using SpeadFrm.Mappers;

namespace JStore.Web.Controllers.CardTypes
{
    public class CardTypesController : BaseController
    {
        private readonly CardTypeTask _cardTypeTask = new CardTypeTask();
        private readonly UserTypeTask _userTypeTask = new UserTypeTask();

        public ActionResult List()
        {
            var model = _cardTypeTask.GetAll()
                .Select(EntityMapper.Map<CardType, CardTypeModel>)
                .ToList();
            var userTypeList = _userTypeTask.GetAll();
            model.ForEach(c =>
                              {
                                  c.UserTypeName = userTypeList.FirstOrDefault(d => d.Id == c.UserTypeId).UserTypeName;
                              });
            return View(model);
        }

        public ActionResult Save(int? id)
        {
            ViewData["CardClassList"] = CardClass.Member.ToSelectList();
            ViewData["UserTypeList"] = _userTypeTask.GetAll().ToSelectList(c => c.Id.ToString(), c => c.UserTypeName);
            var model = new SaveCardTypeModel();
            if (id != null)
            {
                var info = _cardTypeTask.GetById((int)id);
                if (info != null)
                    model = EntityMapper.Map<CardType, SaveCardTypeModel>(info);
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Save(SaveCardTypeModel model)
        {
            if (ModelState.IsValid)
            {
                var cmd = EntityMapper.Map<SaveCardTypeModel, SaveCardTypeCmd>(model);
                string errMsg;
                if (!_cardTypeTask.Save(cmd, out errMsg))
                    return AlertMsg(errMsg, Request.UrlReferrer.PathAndQuery);
                return AlertMsg("保存成功", Request.UrlReferrer.PathAndQuery);
            }
            return AlertMsg("参数异常", Request.UrlReferrer.PathAndQuery);
        }

        [HttpPost]
        public void Delete(int id)
        {
            _cardTypeTask.DeleteById(id);
        }
    }
}